package org.openscheduler.modules.scheduler;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.openscheduler.common.util.KeyGenerator;
import org.springframework.stereotype.Component;

@Component
public class SchedulerRepository {

	private File storeDir;
		public void setStoreDir(File storeDir) {
			if (!storeDir.exists()) {
				storeDir.mkdirs();
			}
			this.storeDir = storeDir;
		}

	public String create(String props) {
		String key = KeyGenerator.createUniqueString(KeyGenerator.createRandomString(10));
		File file = new File(storeDir, key);
		write(file, props);
		return key;
	}
	
	public String get(String id) {
		File file = new File(storeDir, id);
		return read(file);
	}

	public void delete(String id) {
		File file = new File(storeDir, id);
		if (!file.exists()) {
			throw new RuntimeException("File does not exists: " + file.getAbsolutePath());
		}
		if (!file.delete()) {
			throw new RuntimeException("Failed to delete file: " + file.getAbsolutePath());
		}
	}

	public void update(String id, String props) {
		File file = new File(storeDir, id);
		write(file, props);
	}

	public Set<String> getAllIds() {
		Set<String> ids = new HashSet<String>();
		for (File file : storeDir.listFiles()) {
			if (file.isFile()) {
				ids.add(file.getName());
			}
		}
		return ids;
	}

	private void write(File file, String text) {
		FileWriter writer = null;
		try {
			writer = new FileWriter(file);
			IOUtils.write(text, writer);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			IOUtils.closeQuietly(writer);
		}
	}

	private String read(File file) {
		FileReader reader = null;
		try {
			reader = new FileReader(file);
			return IOUtils.toString(reader);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			IOUtils.closeQuietly(reader);
		}
	}

}
